package cn.pet.service.manage.controller;

import cn.pet.service.manage.entity.PetAddress;
import cn.pet.service.manage.entity.api.Result;
import cn.pet.service.manage.service.PetAddressService;
import cn.pet.service.manage.utils.SecurityUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 收货地址表 前端控制器
 * </p>
 *
 * @author 
 * @since 2023-02-11
 */
@RestController
@RequestMapping("/manage/petAddress")
public class PetAddressController {

    @Resource
    private PetAddressService petAddressService;

    /**
     * 根据用户ID查询收货地址列表
     * @param
     * @return
     */
    @GetMapping("listByUserId")
    public Object listByUserId(){
        Integer userId = SecurityUtil.getUserId();
        LambdaQueryWrapper<PetAddress> queryWrap = new LambdaQueryWrapper<>();
        queryWrap.eq(PetAddress::getUserId,userId);
        return Result.ok("查看成功",petAddressService.list(queryWrap));
    }

    /**
     * 获取默认收货地址
     * @return
     */
    @GetMapping("getDefault")
    public Object getDefault(){
        Integer userId = SecurityUtil.getUserId();
        LambdaQueryWrapper<PetAddress> queryWrap = new LambdaQueryWrapper<>();
        queryWrap.eq(PetAddress::getUserId,userId);
        queryWrap.eq(PetAddress :: getLevel,0);
        return Result.ok("查看成功",petAddressService.getOne(queryWrap));
    }

    /**
     * 添加收货地址
     * @param petAddress
     * @return
     */
    @PostMapping("add")
    public Object add(@RequestBody PetAddress petAddress){
        petAddress.setUserId(SecurityUtil.getUserId());
        if (!petAddressService.saveOrUpdate(petAddress)){
            return Result.error("添加失败");
        }
        return Result.ok("添加成功");
    }

    /**
     * 编辑收货地址
     * @param petAddress
     * @return
     */
    @PostMapping("edit")
    public Object edit(@RequestBody PetAddress petAddress) {
        if (!petAddressService.updateById(petAddress)){
            return Result.error("编辑失败");
        }
        return Result.ok("编辑成功");
    }

    /**
     * 查看收货信息
     * @param id
     * @return
     */
    @GetMapping("detail")
    public Object detail(Integer id){
        return Result.ok("查看成功",petAddressService.getById(id));
    }

    /**
     * 删除收货地址
     * @param id
     * @return
     */
    @DeleteMapping("delete")
    public Object delete(Integer id){
        if (!petAddressService.removeById(id)){
            return Result.error("删除失败");
        }
        return Result.ok("删除成功");
    }



}
